Given an unsorted array and a value, remove all instances of that value in-place and return the new length. Problem from LeetCode
In [41]:
# Input1
nums1 = [1,2,3,2]
val1 = 3
In [42]:
# Input2
nums2 = [1]
val2 = 1
In [43]:
def remove_element(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
# Check if nums is empty.
if not nums:
return 0
for i in sorted(nums):
if i == val:
nums.remove(i)
return len(nums)
In [44]:
# Output1
remove_element(nums1, val1)
Out[44]:
In [45]:
# Output2
remove_element(nums2, val2)
Out[45]: